package com.example.websocket.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * @author wwl
 * @version 1.0
 * @date 2024/8/26 14:19
 * @description:
 */
@Slf4j
public class Ws1Handler extends AbstractWebSocketHandler {


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Ws1Pool.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Ws1Pool.remove(session);
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        if ("ping".equals(message.getPayload())) {
            // 心跳消息
            session.sendMessage(new TextMessage("pong"));
            return;
        }
        log.info("receive Msg :" + message.getPayload());
        TextMessage msg = new TextMessage(message.getPayload());
        // 回发信息 给 js前端
        session.sendMessage(msg);
    }
}
